package wcpackage.webapplication.security;

import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.apache.wicket.authorization.IUnauthorizedComponentInstantiationListener;
import wcpackage.domain.dao.UserDAO;
import wcpackage.domain.entities.User;
import wcpackage.webapplication.UserSession;
import wcpackage.webapplication.view.loginpage.LoginPage;

/**
 * User: rabbit
 * Date: Jun 30, 2009
 * Time: 4:54:38 PM
 */
public class UserAuthorizationStrategy implements IAuthorizationStrategy, IUnauthorizedComponentInstantiationListener {

    public UserAuthorizationStrategy(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    private UserDAO userDAO;

    public boolean isInstantiationAuthorized(Class pageClass) {

        if (pageClass.isAnnotationPresent(Secured.class)) {
            Secured secured = (Secured) pageClass.getAnnotation(Secured.class);
            User user = UserSession.get().getUser();
            user = userDAO.getReference(user);
            return user.hasAccesRights(secured.accessRightsCode());
        }
        return true;
    }

    public boolean isActionAuthorized(Component component, Action action) {
        return true;
    }

    public void onUnauthorizedInstantiation(Component component) {
        throw new RestartResponseAtInterceptPageException(
                LoginPage.class);
    }
}
